<template>
  <div class="bill-adjustment-page">
    <div class="wrap">
      <!-- 顶部步骤条 -->
      <StepBar :steps="steps" :current-step="3" />

      <div class="content">
        <!-- 左侧：基本信息、申请信息、解除记录 -->
        <div class="left">
          <!-- 基本信息 -->
          <div class="card">
            <div class="card-title">基本信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="单据编号">{{ formData.elderlyNo }}</el-descriptions-item>
              <el-descriptions-item label="老人姓名">{{ formData.elderlyName }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ formData.elderlyIdCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ formData.contact }}</el-descriptions-item>
              <el-descriptions-item label="费用期限">{{ formData.feePeriod }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="入住床位">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="签约合同">
                {{ formData.contract }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewContract">查看</el-button>
              </el-descriptions-item>
              <el-descriptions-item label="养老顾问">{{ formData.consultant }}</el-descriptions-item>
              <el-descriptions-item label="护理员">{{ formData.caregiver }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 申请信息 -->
          <div class="card">
            <div class="card-title">申请信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="退住日期">{{ formData.checkoutDate }}</el-descriptions-item>
              <el-descriptions-item label="退住原因">{{ formData.checkoutReason }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ formData.remark }}
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ formData.applicantName }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ formData.submitTime }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 解除记录 -->
          <div class="card">
            <div class="card-title">解除记录</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="提交人">{{ formData.terminationSubmitter }}</el-descriptions-item>
              <el-descriptions-item label="解除日期">{{ formData.terminationDate }}</el-descriptions-item>
              <el-descriptions-item label="解除协议" :span="2">
                {{ formData.terminationAgreement }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewTermination">查看</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 调整费用账单 -->
          <div class="card adjustment-card">
            <div class="card-title">调整费用账单</div>
            
            <div class="info-banner">
              <el-icon color="#409eff" style="margin-right: 8px;"><InfoFilled /></el-icon>
              建议关账后生成账单，再在系统中手动修改本账单，若未关账，暂先关账
            </div>

            <!-- 1. 应退 -->
            <div class="bill-section">
              <div class="section-header">
                <span class="section-number">1</span>
                <span class="section-title">应退</span>
              </div>
              
              <div class="bill-item">
                <div class="bill-item-header">
                  <span>账单编号：</span>
                  <el-link type="primary" v-if="bills.refund.items[0].billNo !== '暂无'">{{ bills.refund.items[0].billNo }}</el-link>
                  <span v-else style="color: #999;">{{ bills.refund.items[0].billNo }}</span>
                  <el-button type="primary" link size="small" v-if="bills.refund.items[0].billNo !== '暂无'" @click="calculateActualRefund">自动核算</el-button>
                </div>
                <div class="bill-row">
                  <span class="label">账单月份：</span>
                  <span>{{ bills.refund.items[0].month }}</span>
                  <span class="label ml-40">可退金额：</span>
                  <span>{{ bills.refund.items[0].availableAmount }}元</span>
                </div>
                <div class="bill-row">
                  <span class="label">实缴天数：</span>
                  <span>{{ bills.refund.items[0].actualDays }} 天</span>
                  <span class="label ml-40">退款天数：</span>
                  <span>{{ bills.refund.items[0].refundDays }} 天</span>
                </div>
                <div class="bill-row">
                  <span class="label">实退金额：</span>
                  <el-input-number v-model="bills.refund.items[0].amount" :precision="2" :step="100" :min="0" class="amount-input" :disabled="bills.refund.items[0].billNo === '暂无'" @change="calculateActualRefund" />
                  <span class="label ml-40">调整备注：</span>
                  <el-input v-model="bills.refund.items[0].note" placeholder="请输入" style="width: 200px;" maxlength="50" show-word-limit :disabled="bills.refund.items[0].billNo === '暂无'" />
                </div>
              </div>

            </div>

            <!-- 2. 欠费 -->
            <div class="bill-section">
              <div class="section-header">
                <span class="section-number">2</span>
                <span class="section-title">欠费</span>
              </div>

              <div class="bill-item" v-for="(item, index) in bills.arrears.items" :key="index">
                <div class="bill-item-header">
                  <span>账单编号：</span>
                  <el-link type="primary">{{ item.billNo }}</el-link>
                  <el-button type="primary" link size="small">月度账单</el-button>
                </div>
                <div class="bill-row">
                  <span class="label">账单月份：</span>
                  <span>{{ item.month }}</span>
                </div>
                <div class="bill-row">
                  <span class="label">应付金额：</span>
                  <span>{{ item.amount }} 元</span>
                </div>
              </div>
            </div>

            <!-- 3. 杂费 -->
            <div class="bill-section">
              <div class="section-header">
                <span class="section-number">3</span>
                <span class="section-title">杂费</span>
              </div>

              <div class="misc-fee-row">
                <span class="label">可退押金：</span>
                <span class="value">{{ bills.misc.deposit }} 元</span>
                <span class="label ml-60">实退金额：</span>
                <el-input-number v-model="bills.misc.deposit" :precision="2" :step="100" :min="0" class="amount-input" />
                <span class="label ml-40">调整备注：</span>
                <el-input v-model="bills.misc.depositNote" placeholder="请输入" style="width: 200px;" maxlength="50" show-word-limit />
              </div>

              <div class="misc-fee-row">
                <span class="label">押金数：</span>
                <span class="value">{{ bills.misc.deposit }} 元</span>
              </div>
            </div>

            <!-- 总计提示 -->
            <div class="total-alert">
              <el-icon color="#f56c6c" style="margin-right: 8px;"><WarningFilled /></el-icon>
              <span>实际应退金额 = 应退 - 欠费 + 押金数 = {{ calculatedAmount }} 元</span>
            </div>
          </div>
        </div>

        <!-- 右侧：操作记录 -->
        <div class="right">
          <div class="card">
            <div class="card-title">操作记录</div>
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">发起申请-申请退住</div>
                    <div class="timeline-date">{{ formData.submitTime }}</div>
                  </div>
                  <div class="timeline-user">
                    {{ formData.applicantName }}
                    <el-tag size="small" type="success">已发起</el-tag>
                  </div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">(待处理) 审批-申请审批</div>
                    <div class="timeline-date">2048-10-15 09:00:00</div>
                  </div>
                  <div class="timeline-user">
                    退住审批员
                    <el-tag size="small" type="success">已通过</el-tag>
                  </div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-icon pending">⏱</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">这是当前操作处</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="bottom-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled, WarningFilled } from '@element-plus/icons-vue'
import StepBar from '@/components/StepBar/index.vue'
import { getCheckoutApplicationDetail } from '@/api/system/approval'
import { getContractByElderlyId, submitBillAdjustment } from '@/api/system/out_management'
import { getCheckoutMonthBill, getOverdueBills, getBalanceByElderlyId, updatePrepaymentBalance } from '@/api/system/bill'
import { updateTasks } from '@/api/system/tasks'

const router = useRouter()
const route = useRoute()

// 步骤条数据
const steps = ['申请退住', '申请审批', '解除合同', '调整账单', '账单审批', '退住审批', '费用清算']

// 基本信息和申请信息数据
const formData = ref({
  elderlyId: null, // 老人ID，用于更新余额
  elderlyNo: 'TZ204810101S000001',
  elderlyName: '高启强',
  elderlyIdCard: '230203197702221029',
  contact: '13898988888',
  feePeriod: '2048-10-10 —— 2049-10-10',
  careLevel: '特级护理等级',
  bedNumber: '101床位',
  contract: '高启强长住合同.pdf',
  consultant: '顾廷烨',
  caregiver: '盛长柏、盛明兰、盛如兰',
  checkoutDate: '2048-10-15',
  checkoutReason: '服务不周',
  remark: '已和家属沟通过，若高龄先生回归后，将重新办理入住',
  applicantName: '顾廷烨',
  submitTime: '2048-10-05 15:00:00',
  terminationSubmitter: '顾廷烨',
  terminationDate: '2024-05-05',
  terminationAgreement: '高启强解除协议.pdf'
})

// 页面加载时从URL参数查询业务数据
onMounted(async () => {
  console.log('=== 账单调整页面加载开始 ===')
  console.log('URL参数:', route.query)
  console.log('完整路由信息:', route)
  
  // 优先从后端API获取数据（根据业务ID查询）
  console.log('=== 优先从后端API获取数据 ===')
  
  if (route.query.id) {
    const businessId = route.query.id
    console.log('使用业务ID从后端获取数据:', businessId)
    
    try {
      const response = await getCheckoutApplicationDetail(businessId)
      console.log('后端返回的申请详情:', response)
      
      if (response.code === 200 && response.data) {
        const appData = response.data
        console.log('解析后的申请数据:', appData)
        
        // 使用后端数据更新表单
        formData.value = {
          elderlyId: appData.elderlyId || null, // 老人ID，用于更新余额
          elderlyNo: appData.checkOutNo || 'TZ' + businessId,
          elderlyName: appData.elderlyName || '未知老人',
          elderlyIdCard: appData.elderlyIdCard || '未知身份证',
          contact: appData.elderlyContact || '未知联系方式',
          feePeriod: (appData.feeStartDate && appData.feeEndDate) ? 
            `${appData.feeStartDate} —— ${appData.feeEndDate}` : '未知费用期限',
          careLevel: appData.careLevel || '未知护理等级',
          bedNumber: appData.bedNumber || '未知床位',
          contract: appData.contractName || '未知合同',
          consultant: appData.caregiverName || '未知顾问',
          caregiver: appData.caregiverName || '未知护理员',
          checkoutDate: appData.checkOutDate || '未知退住日期',
          checkoutReason: appData.checkOutReason || '未知退住原因',
          remark: appData.remark || '无备注',
          applicantName: appData.creatorName || '护理员a',
          submitTime: appData.createTime || new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-'),
          terminationSubmitter: '顾廷烨', // TODO: 从合同表获取
          terminationDate: '2024-05-05', // TODO: 从合同表获取
          terminationAgreement: '高启强解除协议.pdf' // TODO: 从合同表获取
        }
        
        console.log('使用后端数据更新表单:', formData.value)
        
        // 如果有老人ID，尝试获取合同信息
        if (appData.elderlyId) {
          try {
            console.log('=== 获取合同信息 ===')
            console.log('老人ID:', appData.elderlyId)
            
            const contractResponse = await getContractByElderlyId(appData.elderlyId)
            console.log('合同API响应:', contractResponse)
            
            if (contractResponse.code === 200 && contractResponse.data) {
              const contractData = contractResponse.data
              console.log('合同数据:', contractData)
              
              // 更新合同名称
              if (contractData.contractName) {
                formData.value.contract = contractData.contractName
                console.log('合同名称:', contractData.contractName)
              }
              
              // ✅ 更新解除记录信息（从合同表获取）
              console.log('=== 解除记录信息 ===')
              
              // 解除日期
              if (contractData.terminationTime) {
                const terminationDate = new Date(contractData.terminationTime)
                formData.value.terminationDate = terminationDate.toLocaleDateString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit'
                }).replace(/\//g, '-')
                console.log('解除日期:', formData.value.terminationDate)
              }
              
              // 解除协议
              if (contractData.terminationAgreement) {
                formData.value.terminationAgreement = contractData.terminationAgreement
                console.log('解除协议:', formData.value.terminationAgreement)
              }
              
              // 解除提交人（需要通过用户ID获取昵称）
              if (contractData.terminationSubmitter) {
                console.log('解除提交人ID:', contractData.terminationSubmitter)
                
                // 如果合同数据中有关联的用户信息
                if (contractData.sysUser && contractData.sysUser.nickName) {
                  formData.value.terminationSubmitter = contractData.sysUser.nickName
                  console.log('解除提交人昵称:', formData.value.terminationSubmitter)
                } else {
                  // 如果没有关联数据，可以显示用户ID或默认值
                  formData.value.terminationSubmitter = '护理员a'
                  console.log('解除提交人（默认）:', formData.value.terminationSubmitter)
                }
              }
              
            console.log('=== 解除记录信息获取完成 ===')
          }
          
          console.log('=== 合同信息获取完成 ===')
        } catch (contractError) {
          console.error('获取合同信息失败:', contractError)
        }
      }
      
      // ✅ 查询退住当月账单（第一个卡片：应退）
      if (appData.elderlyId && appData.checkOutDate) {
        try {
          console.log('=== 查询退住当月账单 ===')
          console.log('老人ID:', appData.elderlyId)
          console.log('退住日期:', appData.checkOutDate)
          
          const billResponse = await getCheckoutMonthBill(appData.elderlyId, appData.checkOutDate)
          console.log('账单API响应:', billResponse)
          
          if (billResponse.code === 200 && billResponse.data) {
            const billData = billResponse.data
            console.log('账单数据:', billData)
            console.log('账单编号（bill_no）:', billData.billNo)
            console.log('账单月份（bill_month）:', billData.billMonth)
            console.log('实缴天数:', billData.actualDays)
            console.log('退款天数:', billData.refundDays)
            console.log('可退金额:', billData.refundableAmount)
            console.log('账单状态:', billData.status)
            
            // ✅ 根据账单状态显示不同数据
            bills.refund.items[0] = {
              billNo: billData.billNo || '暂无',        // ✅ 数据库的 bill_no
              month: billData.billMonth || '暂无',      // ✅ 数据库的 bill_month
              availableAmount: billData.refundableAmount || 0,
              actualDays: billData.actualDays || 0,
              refundDays: billData.refundDays || 0,
              amount: billData.refundableAmount || 0,
              note: '',
              status: billData.status || '未知'          // ✅ 账单状态
            }
            
            console.log('✅ 账单数据已更新:', bills.refund.items[0])
            console.log('✅ 显示的账单编号:', bills.refund.items[0].billNo)
            console.log('✅ 显示的账单月份:', bills.refund.items[0].month)
            console.log('✅ 账单状态:', bills.refund.items[0].status)
            
            // 根据状态显示不同的提示信息
            if (billData.status === '已支付') {
              console.log('✅ 账单已支付，显示实际数据')
              // 自动计算实退金额
              calculateActualRefund()
            } else if (billData.status === '待支付' || billData.status === '已关闭') {
              console.log('✅ 账单状态为' + billData.status + '，显示暂无数据')
            } else {
              console.log('⚠️ 未知账单状态:', billData.status)
            }
          } else {
            // ✅ 如果查不到账单，显示"暂无"
            console.log('未找到退住当月的账单数据，显示暂无')
            
            bills.refund.items[0] = {
              billNo: '暂无',
              month: '暂无',
              availableAmount: 0,
              actualDays: 0,
              refundDays: 0,
              amount: 0,
              note: '',
              status: '无账单'
            }
            
            console.log('✅ 设置为暂无数据:', bills.refund.items[0])
          }
          
          console.log('=== 账单查询完成 ===')
        } catch (billError) {
          console.error('查询账单失败:', billError)
        }
      } else {
        console.log('缺少老人ID或退住日期，无法查询账单')
        
        // 如果缺少必要参数，设置为暂无
        bills.refund.items[0] = {
          billNo: '暂无',
          month: '暂无',
          availableAmount: 0,
          actualDays: 0,
          refundDays: 0,
          amount: 0,
          note: '',
          status: '无数据'
        }
      }
      
      // ✅ 查询待支付账单（第二个卡片：欠费）
      if (appData.elderlyId) {
        try {
          console.log('=== 查询待支付账单 ===')
          console.log('老人ID:', appData.elderlyId)
          
          const overdueResponse = await getOverdueBills(appData.elderlyId)
          console.log('待支付账单API响应:', overdueResponse)
          
          if (overdueResponse.code === 200 && overdueResponse.data) {
            const overdueBills = overdueResponse.data
            console.log('待支付账单数据:', overdueBills)
            console.log('待支付账单数量:', overdueBills.length)
            
            // 更新欠费卡片数据
            bills.arrears.items = overdueBills.map((bill, index) => ({
              billNo: bill.billNo || '暂无',
              month: bill.billMonth || '暂无',
              amount: bill.payableAmount || 0,
              status: bill.status || '待支付'
            }))
            
            console.log('✅ 欠费账单数据已更新:', bills.arrears.items)
          } else {
            console.log('未找到待支付账单数据')
            bills.arrears.items = []
          }
          
          console.log('=== 待支付账单查询完成 ===')
        } catch (overdueError) {
          console.error('查询待支付账单失败:', overdueError)
          bills.arrears.items = []
        }
      } else {
        console.log('缺少老人ID，无法查询待支付账单')
        bills.arrears.items = []
      }
      
      // ✅ 查询老人余额信息（第三个卡片：杂费）
      if (appData.elderlyId) {
        try {
          console.log('=== 查询老人余额信息 ===')
          console.log('老人ID:', appData.elderlyId)
          
          const balanceResponse = await getBalanceByElderlyId(appData.elderlyId)
          console.log('余额信息API响应:', balanceResponse)
          
          if (balanceResponse.code === 200 && balanceResponse.data) {
            const balanceData = balanceResponse.data
            console.log('余额信息数据:', balanceData)
            console.log('押金余额:', balanceData.depositBalance)
            console.log('预交款余额:', balanceData.prepaymentBalance)
            
            // ✅ 保存完整的balance数据
            balanceInfo.elderlyId = appData.elderlyId
            balanceInfo.depositBalance = balanceData.depositBalance || 0
            balanceInfo.prepaymentBalance = balanceData.prepaymentBalance || 0
            balanceInfo.totalBalance = balanceData.totalBalance || 0
            
            console.log('✅ Balance信息已保存:', balanceInfo)
            
            // 更新杂费卡片数据
            const depositAmount = balanceData.depositBalance || 0
            bills.misc.deposit = depositAmount        // 可退押金 = 押金余额 = 实退金额 = 押金数
            bills.misc.depositNote = ''               // 重置备注
            
            console.log('✅ 杂费卡片数据已更新:', {
              deposit: bills.misc.deposit
            })
          } else {
            console.log('未找到余额信息数据，使用默认值')
            bills.misc.deposit = 0
            bills.misc.depositNote = ''
            balanceInfo.depositBalance = 0
            balanceInfo.prepaymentBalance = 0
          }
          
          console.log('=== 余额信息查询完成 ===')
        } catch (balanceError) {
          console.error('查询余额信息失败:', balanceError)
          bills.misc.deposit = 0
          bills.misc.depositNote = ''
        }
      } else {
        console.log('缺少老人ID，无法查询余额信息')
        bills.misc.deposit = 0
        bills.misc.depositNote = ''
      }
      
      console.log('=== 数据加载完成 ===')
      console.log('最终基本信息数据:', formData.value)
      console.log('最终账单数据:', bills.refund.items[0])
      console.log('最终欠费数据:', bills.arrears.items)
      console.log('最终杂费数据:', bills.misc)
    }
  } catch (apiError) {
    console.error('后端API调用失败:', apiError)
  }
} else {
  console.log('警告：没有业务ID参数')
}

console.log('=== 账单调整页面加载完成 ===')
})

// 账单数据
const bills = reactive({
  // 应退
  refund: {
    items: [
      {
        billNo: 'ZD204810101S000001',
        month: '2048-10',
        availableAmount: 2000.00,
        actualDays: 18,
        refundDays: 12,
        amount: 2000.00,
        note: '',
        status: '已支付'
      }
    ]
  },
  // 欠费
  arrears: {
    items: []
  },
  // 杂费
  misc: {
    deposit: 0,
    depositNote: ''
  }
})

// ✅ 老人余额信息（balance表数据）
const balanceInfo = reactive({
  elderlyId: null,
  depositBalance: 0,      // 押金余额
  prepaymentBalance: 0,   // 预交款余额
  totalBalance: 0         // 总余额（如果有）
})

// 计算实际应退金额
const calculatedAmount = computed(() => {
  try {
    // 应退金额：取第一个应退项目的实退金额
    const refundAmount = bills.refund.items.length > 0 ? (bills.refund.items[0].amount || 0) : 0
    
    // 欠费金额：所有欠费项目的应付金额之和
    const arrearsAmount = bills.arrears.items.reduce((total, item) => {
      return total + (item.amount || 0)
    }, 0)
    
    // 押金数：杂费中的押金数
    const depositAmount = bills.misc.deposit || 0
    
    // 计算公式：实际应退金额 = 应退 - 欠费 + 押金数
    const result = refundAmount - arrearsAmount + depositAmount
    
    console.log('=== 实际应退金额计算 ===')
    console.log('应退金额:', refundAmount)
    console.log('欠费金额:', arrearsAmount)
    console.log('押金数:', depositAmount)
    console.log('bills.misc对象:', bills.misc)
    console.log('计算结果:', result)
    
    return result.toFixed(2)
  } catch (error) {
    console.error('计算实际应退金额失败:', error)
    return '0.00'
  }
})

// 计算实退金额
const calculateActualRefund = () => {
  try {
    const refundItem = bills.refund.items[0]
    if (refundItem && refundItem.billNo !== '暂无') {
      const refundDays = refundItem.refundDays || 0
      const availableAmount = refundItem.availableAmount || 0
      
      // 计算公式：实退金额 = (退款天数 / 30) × 可退金额
      const calculatedAmount = (refundDays / 30) * availableAmount
      
      console.log('=== 实退金额计算 ===')
      console.log('退款天数:', refundDays)
      console.log('可退金额:', availableAmount)
      console.log('计算公式: (退款天数 / 30) × 可退金额')
      console.log('计算结果:', calculatedAmount)
      
      // 更新实退金额
      refundItem.amount = parseFloat(calculatedAmount.toFixed(2))
      
      console.log('✅ 实退金额已更新为:', refundItem.amount)
    }
  } catch (error) {
    console.error('计算实退金额失败:', error)
  }
}

// 查看合同
const viewContract = () => {
  ElMessage.info('查看合同文件：高启强长住合同.pdf')
}

// 查看解除协议
const viewTermination = () => {
  ElMessage.info('查看解除协议：高启强解除协议.pdf')
}

// 返回
const handleBack = () => {
  // 返回到待办任务列表
  router.push('/xtgz/xtgz/tasks')
}

// 提交
const handleSubmit = async () => {
  try {
    await ElMessageBox.confirm(
      '确认提交账单调整吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 准备提交数据
    const submitData = {
      businessId: route.query.id, // 业务ID
      taskId: route.query.taskId || '', // 工作流任务ID
      ptId: route.query.ptid || '' // 待办任务ID
    }
    
    console.log('=== 账单调整提交 ===')
    console.log('提交数据:', submitData)
    console.log('业务ID:', submitData.businessId)
    console.log('任务ID:', submitData.taskId)
    console.log('待办任务ID:', submitData.ptId)
    
    // 调用后端API
    const response = await submitBillAdjustment(submitData)
    
    if (response.code === 200) {
      ElMessage.success('账单调整已提交！')
      
      // ✅ 保存账单数据到sessionStorage，供第五步使用
      console.log('=== 保存账单数据到sessionStorage ===')
      const billDataForNextStep = {
        // 老人ID（用于后续查询）
        elderlyId: formData.value.elderlyId,
        // 应退卡片数据
        refund: {
          items: bills.refund.items.map(item => ({
            billNo: item.billNo,
            month: item.month,
            availableAmount: item.availableAmount,
            actualDays: item.actualDays,
            refundDays: item.refundDays,
            amount: item.amount,
            note: item.note,
            status: item.status
          }))
        },
        // 欠费卡片数据
        arrears: {
          items: bills.arrears.items.map(item => ({
            billNo: item.billNo,
            month: item.month,
            amount: item.amount,
            status: item.status
          }))
        },
        // 杂费卡片数据
        misc: {
          deposit: bills.misc.deposit,
          depositNote: bills.misc.depositNote
        },
        // ✅ 添加：老人余额信息（balance表数据）
        balance: {
          elderlyId: balanceInfo.elderlyId,
          depositBalance: balanceInfo.depositBalance,     // 押金余额
          prepaymentBalance: balanceInfo.prepaymentBalance, // 预交款余额
          totalBalance: balanceInfo.totalBalance           // 总余额
        },
        // 计算出的总金额
        totalAmount: calculatedAmount.value,
        // 保存时间戳
        timestamp: new Date().getTime()
      }
      
      // 保存到sessionStorage（使用业务ID作为key的一部分）
      const storageKey = `bill_adjustment_data_${route.query.id}`
      sessionStorage.setItem(storageKey, JSON.stringify(billDataForNextStep))
      console.log('账单数据已保存到sessionStorage:', storageKey)
      console.log('保存的数据:', billDataForNextStep)
      
      // ✅ 更新老人预交款余额
      console.log('=== 更新老人预交款余额 ===')
      console.log('实际应退金额:', calculatedAmount.value)
      console.log('实际应退金额类型:', typeof calculatedAmount.value)
      
      try {
        // 获取老人ID（从表单数据中获取）
        const elderlyId = formData.elderlyId
        if (elderlyId && calculatedAmount.value !== '0.00' && calculatedAmount.value !== 0) {
          console.log('老人ID:', elderlyId)
          console.log('实际应退金额:', calculatedAmount.value)
          
          // 确保refundAmount是数字类型
          const refundAmount = parseFloat(calculatedAmount.value)
          console.log('转换后的退款金额:', refundAmount)
          
          // 调用更新预交款余额API
          const balanceUpdateData = {
            elderlyId: elderlyId,
            refundAmount: refundAmount
          }
          
          console.log('更新余额数据:', balanceUpdateData)
          
          const balanceResponse = await updatePrepaymentBalance(balanceUpdateData)
          console.log('余额更新响应:', balanceResponse)
          
          if (balanceResponse.code === 200) {
            console.log('✅ 老人预交款余额更新成功！')
            ElMessage.success('老人预交款余额已更新！')
          } else {
            console.error('❌ 老人预交款余额更新失败:', balanceResponse.msg)
            ElMessage.warning('账单调整成功，但余额更新失败：' + balanceResponse.msg)
          }
        } else {
          console.log('跳过余额更新：老人ID为空或实际应退金额为0')
          console.log('老人ID:', elderlyId)
          console.log('实际应退金额:', calculatedAmount.value)
        }
      } catch (balanceError) {
        console.error('更新老人预交款余额异常:', balanceError)
        ElMessage.warning('账单调整成功，但余额更新异常：' + balanceError.message)
      }
      
      // ✅ 重写：使用最简单直接的方法更新状态
      console.log('=== 重写第四步状态更新逻辑 ===')
      console.log('待办任务ID:', submitData.ptId)
      
      // 方法1：直接调用后端API更新状态
      try {
        console.log('方法1：直接调用后端API更新状态')
        
        // 使用最简单的数据格式
        const simpleUpdateData = {
          id: submitData.ptId,
          isHandle: 1
        }
        
        console.log('简单更新数据:', simpleUpdateData)
        
        const updateResponse = await updateTasks(simpleUpdateData)
        console.log('更新响应:', updateResponse)
        
        if (updateResponse.code === 200) {
          console.log('✅ 方法1成功：第四步待办任务状态更新成功！')
          ElMessage.success('第四步待办任务状态已更新！')
        } else {
          console.error('❌ 方法1失败:', updateResponse.msg)
          throw new Error('方法1失败')
        }
        
      } catch (method1Error) {
        console.error('❌ 方法1异常:', method1Error)
        
        // 方法2：使用更简单的数据格式
        try {
          console.log('方法2：使用更简单的数据格式')
          
          const minimalUpdateData = {
            id: submitData.ptId,
            isHandle: 1,
            updateTime: new Date().getTime() // 使用时间戳
          }
          
          console.log('最小更新数据:', minimalUpdateData)
          
          const updateResponse2 = await updateTasks(minimalUpdateData)
          console.log('更新响应2:', updateResponse2)
          
          if (updateResponse2.code === 200) {
            console.log('✅ 方法2成功：第四步待办任务状态更新成功！')
            ElMessage.success('第四步待办任务状态已更新！')
          } else {
            console.error('❌ 方法2失败:', updateResponse2.msg)
            throw new Error('方法2失败')
          }
          
        } catch (method2Error) {
          console.error('❌ 方法2异常:', method2Error)
          
          // 方法3：只更新必要字段
          try {
            console.log('方法3：只更新必要字段')
            
            const essentialUpdateData = {
              id: submitData.ptId,
              isHandle: 1,
              status: 1
            }
            
            console.log('必要更新数据:', essentialUpdateData)
            
            const updateResponse3 = await updateTasks(essentialUpdateData)
            console.log('更新响应3:', updateResponse3)
            
            if (updateResponse3.code === 200) {
              console.log('✅ 方法3成功：第四步待办任务状态更新成功！')
              ElMessage.success('第四步待办任务状态已更新！')
            } else {
              console.error('❌ 方法3失败:', updateResponse3.msg)
              ElMessage.warning('账单调整提交成功，但状态更新失败')
            }
            
          } catch (method3Error) {
            console.error('❌ 方法3异常:', method3Error)
            ElMessage.warning('账单调整提交成功，但状态更新异常')
          }
        }
      }
      
      // 提交后跳转到下一步：账单审批页面（步骤5）
      // ✅ 需要传递第五步所需的参数
      setTimeout(() => {
        router.push({
          path: '/splccs/zdtzh',
          query: {
            id: route.query.id, // 业务ID
            taskId: response.data?.nextTaskId || '', // 第五步的工作流任务ID
            ptid: response.data?.nextPtId || '', // 第五步的待办任务ID
            step: 5,
            type: route.query.type || 1
          }
        })
      }, 1000)
    } else {
      ElMessage.error(response.msg || '提交失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交异常:', error)
      ElMessage.error('提交失败：' + (error.message || '未知错误'))
    }
  }
}
</script>

<style scoped lang="scss">
.bill-adjustment-page {
  min-height: 100%;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 50%, #fffde7 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;

  &::before,
  &::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    opacity: 0.3;
    pointer-events: none;
  }

  &::before {
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(205, 220, 57, 0.3) 0%, transparent 70%);
    top: 100px;
    left: 10%;
  }

  &::after {
    width: 300px;
    height: 300px;
    background: radial-gradient(circle, rgba(139, 195, 74, 0.25) 0%, transparent 70%);
    top: 200px;
    right: 15%;
  }
}

.wrap {
  max-width: 1400px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.content {
  display: grid;
  grid-template-columns: 1fr 450px;
  gap: 20px;
  margin-bottom: 20px;
}

.left,
.right {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
}

:deep(.desc) {
  .desc-label {
    background: #fafafa;
    color: #666;
    font-weight: normal;
    text-align: right;
  }
}

/* 调整账单卡片 */
.adjustment-card {
  padding: 25px;
}

.info-banner {
  background: #ecf5ff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #409eff;
}

/* 账单区块 */
.bill-section {
  margin-bottom: 25px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 15px;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;

  .section-number {
    width: 24px;
    height: 24px;
    background: #f56c6c;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin-right: 10px;
  }

  .section-title {
    font-weight: bold;
    color: #333;
    flex: 1;
  }

  .section-amount {
    color: #666;
    margin-right: 20px;
  }

  .section-total {
    font-weight: bold;
    color: #f56c6c;
  }
}

.bill-item {
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 12px;

  &:last-child {
    margin-bottom: 0;
  }
}

.bill-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
  font-size: 14px;

  span {
    color: #666;
  }

  .el-link {
    margin: 0 10px;
  }

  .el-button {
    margin-left: auto;
  }
}

.bill-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    color: #666;
    min-width: 80px;
  }

  .ml-40 {
    margin-left: 40px;
  }

  .ml-60 {
    margin-left: 60px;
  }
}

.amount-input {
  width: 150px;
}

/* 杂费行 */
.misc-fee-row {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 12px;
  font-size: 13px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    color: #666;
  }

  .value {
    color: #333;
    font-weight: 500;
    margin-right: 20px;
  }
}

/* 总计提示 */
.total-alert {
  background: #fef0f0;
  border: 1px solid #fde2e2;
  border-radius: 4px;
  padding: 12px 16px;
  margin-top: 20px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
}

/* 时间轴样式 */
.timeline {
  .timeline-item {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 21px;
      top: 45px;
      bottom: -25px;
      width: 2px;
      background: #e0e0e0;
    }
  }

  .timeline-icon {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    flex-shrink: 0;

    &.success {
      background: #67c23a;
    }

    &.pending {
      background: #409eff;
    }
  }

  .timeline-content {
    flex: 1;
    padding-top: 2px;
  }

  .timeline-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    align-items: center;
  }

  .timeline-title {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .timeline-date {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
  }

  .timeline-user {
    font-size: 13px;
    color: #666;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

/* 底部按钮 */
.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

@media (max-width: 1200px) {
  .content {
    grid-template-columns: 1fr;
  }
}
</style>

